package com.cat.orm.core.db.factory;

import com.cat.orm.core.annotation.DataConverter;
import com.cat.orm.core.base.BasePo;
import com.cat.orm.core.base.IBaseData;
import com.cat.orm.core.convert.PersistenceDataConverter;
import com.cat.orm.core.convert.SimpleDataJsonConvert;
import com.cat.orm.core.db.dao.CommonDao;
import com.cat.orm.core.db.dao.ConvertDao;
import com.cat.orm.core.db.dao.DelayConvertDao;
import com.cat.orm.core.db.dao.IDao;
import org.springframework.jdbc.core.JdbcTemplate;

/**
 * 转换dao工厂
 */
public class DelayConvertDaoFactory implements DaoFactory {

    @Override
    public Class<? extends IDao> daoClazz() {
        return DelayConvertDao.class;
    }

    public <T extends IBaseData> IDao<T> createDao(Class<T> clazz, JdbcTemplate jdbcTemplate, String tableName) throws Exception {
        DataConverter dataConverter = clazz.getAnnotation(DataConverter.class);
        Class<? extends PersistenceDataConverter> converterClazz = dataConverter.value();
        PersistenceDataConverter<T, BasePo> converter = null;
        if (SimpleDataJsonConvert.class.isAssignableFrom(converterClazz)){
            converter = new SimpleDataJsonConvert(clazz);
        }else{
            converter = converterClazz.getConstructor().newInstance();
        }
        return new DelayConvertDao<>(new CommonDao<>(converter.getPojoClazz(), jdbcTemplate, tableName), converter);
    }
}